 package com.cypher.encryptionanddecryption.util;

import android.widget.Toast;

import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;

import org.apache.commons.lang3.StringUtils;

/**
 * 昆仑通信协议工具类
 * @author: 古霸天
 * @date: 2020/11/17
 */
public class KunLunProtocolUtils {

    public static final String conSelf = "0F";
    /**
     * 无后续帧
     */
    public static final String conCon06 = "06";
    public static final String conPro = "0200";
    /**
     * 表号超级地址
     */
    public static final String conSuper = "AAAAAAAAAAAAAAAA";
    /**
     * 登录认证Token
     */
    public static final String str_Con_Token = "0000000000000000";

    /**
     * 本地通讯激活
     */
    public static final String  str_Con_Open = "01";
    /**
     * 本地通讯关闭
     */
    public static final String  str_Con_Close = "02";

    /**
     * 获取特殊情况下的昆仑发送码
     * @param command
     * @return
     */
    public static String getKunLunSpecialCommand(String command) {
        // 计算数据帧长度
        String dataFrame = HexUtils.intToHex((command.length() / 2), 2);
        command = dataFrame + command;
        command = conSelf + command;
        return getKunLunCommand(command);
    }
    /**
     * 根据命令获取昆仑发送码
     * @param command
     * @return
     */
    public static String getKunLunCommand(String command) {

        // 接收返回值
        String result = "";

        result = conPro + conSuper + conCon06 + HexUtils.hexOrA5(command);

        result = HexUtils.intToHex(result.length() / 2 + 5, 4) + result;

        result = ProtocolUtils.con188Star + result + HexUtils.crc16(HexUtils.hexToBytes(result)) + ProtocolUtils.con188End;

        return result;
    }

    /**
     * 激活红外
     * @param gattManager
     *      发送数据蓝牙连接类
     * @return
     */
    public static void wakeUpInfrared(BluetoothGattManager gattManager) {
        // 激活红外数据域
        String command = str_Con_Open + conSuper + str_Con_Token;
        command = getKunLunCommand(command);
        // 向列表添加数据
        gattManager.addList("<- " + HexUtils.formatHex(command));
        // 向蓝牙发送数据
        gattManager.sendMsg(HexUtils.hexToBytes(command));
    }

    /**
     * 格式化接收数据
     * @param data
     * @return
     */
    public static String formatReceiveData(String data) {
        int index = data.indexOf("68");
        // 截取多余的头帧
        data = StringUtils.substring(data, index);
        // 数据域进行A5异或
        return HexUtils.hexOrA5(StringUtils.substring(data, 28, data.length() - 6));
    }

    /**
     * 校验写入数据是否成功
     * @param data
     * @return
     */
    public static boolean checkWriteDataStatus(String data) {
        // 格式化数据
        String formatData = KunLunProtocolUtils.formatReceiveData(data);
        if (StringUtils.equals("9000" , formatData.substring(2, 6))) {
            return true;
        }
        return false;
    }
}
